//
//  BaseViewController.m
//  BaseFrame
//
//  Created by apple on 16/9/28.
//  Copyright © 2016年 com.mxh. All rights reserved.
//

#import "BaseViewController.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "LoginViewController.h"

@interface BaseViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic,copy) void(^selectPhotoHandle)(UIImage *img);

@end

@implementation BaseViewController
//设置状态栏颜色
//- (void)setStatusBarBackgroundColor:(UIColor *)color {
//
//    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
//    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
//        statusBar.backgroundColor = color;
//    }
//}
//// 视图将要出现   导航栏显示
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}
//- (void)viewWillDisappear:(BOOL)animated
//{
//    self.navigationController.navigationBar.hidden = NO;
//}
- (void)viewDidLoad {
    [super viewDidLoad];
//    [self setStatusBarBackgroundColor:[UIColor redColor]];
    
    //布局 不延伸
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    //导航栏下的横线
//    [self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:getColor(whiteColor)]];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setTranslucent:NO];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    // 状态栏和导航栏字体全变为白色
//    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    // 导航栏字体颜色
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:getColor(textColor)};
    // 设置导航栏背景颜色
//    self.navigationController.navigationBar.barTintColor = getColor(mainColor);
    self.navigationController.navigationBar.barTintColor = getColor(whiteColor);
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];  // 设置渐变效果
//    gradientLayer.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 64);
//    gradientLayer.position = CGPointMake(SCREEN_WIDTH/ 2, 32);
//    gradientLayer.colors = [NSArray arrayWithObjects:(id)[getColor(@"468df2") CGColor],(id)[getColor(@"5abcf9") CGColor], nil];
//    gradientLayer.startPoint = CGPointMake(0, 0.5);
//    gradientLayer.endPoint = CGPointMake(1.0, 0.5);
//    [[[self.navigationController.navigationBar.subviews firstObject] layer] addSublayer:gradientLayer];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"";
    self.navigationItem.backBarButtonItem = backItem;
    
}

- (MBProgressHUD *)progressHUD {
    if (!_progressHUD) {
        _progressHUD = [[MBProgressHUD alloc]initWithView:self.view];
        //        _progressHUD.frame = [UIScreen mainScreen].bounds;
        //        _progressHUD.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.75];
    }
    return _progressHUD;
}

#pragma mark - Custom Method
/**
 *  显示错误的code码和信息
 *
 *  @param status    返回的code码
 *  @param message 返回的信息
 */
- (void) failureWithStatus:(NSString*)status message:(NSString*)message{
    NSLog(@"status:%@,msg:%@", status,message);
}

/**
 *  显示错误信息
 *
 *  @param error 返回的错误信息
 */
- (void) showError:(NSError*)error{
    switch (error.code) {
        case NSURLErrorNotConnectedToInternet:
            ShowMessage(@"请检查你的网络");
            break;
        case NSURLErrorTimedOut:
            ShowMessage(@"请求超时，请查看你的网络");
            break;
        case NSURLErrorCannotConnectToHost:
            ShowMessage(@"服务器繁忙，请稍后重试");
            break;
        case NSURLErrorNetworkConnectionLost:
            ShowMessage(@"处理过程中网络中断，请重试");
            break;
        default:
            ShowMessage(@"未知错误");
            break;
    }
}

/**
 *  显示大菊花
 */
-(void)showprogressHUD{
    self.tabBarController.view.userInteractionEnabled = NO;
    self.navigationController.view.userInteractionEnabled = NO;
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self.navigationController.view addSubview:self.progressHUD];
    [self.progressHUD showAnimated:YES];
}

/**
 *  隐藏大菊花
 */
-(void)hiddenProgressHUD{
    self.tabBarController.view.userInteractionEnabled = YES;
    self.navigationController.view.userInteractionEnabled = YES;
    [self.progressHUD hideAnimated:YES];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self.progressHUD removeFromSuperview];
}

/**
 弹出提示框 选择相机或者相册
 
 @param selectPhotoHandle 选中或拍摄的图片
 */
- (void)selectPhotoAlbumWithSelectPhotoHandle:(void (^)(UIImage *))selectPhotoHandle{
    self.selectPhotoHandle = selectPhotoHandle;
    
    UIAlertController *av = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self LocalPhoto];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [av addAction:action1];
    [av addAction:action2];
    [av addAction:cancelAction];
    [self presentViewController:av animated:YES completion:nil];
}

//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    if (self.selectPhotoHandle) {
        self.selectPhotoHandle(image);
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

/**
 *  拨打电话
 *
 *  @param phoneNumber 号码
 */
- (void)callPhone:(NSString *)phoneNumber{
//    UIAlertController *av = [UIAlertController alertControllerWithTitle:@"拨打电话" message:nil preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
//    }];
//    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//
//    }];
//    [av addAction:action1];
//    [av addAction:action2];
//    [self presentViewController:av animated:YES completion:nil];
}
- (BOOL) isLoginIn
{
    if ([[UserModel sharedInstanced].userId isEqualToString:@""] || ![UserModel sharedInstanced].userId) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
//        [self.mineView cancelBtnClick];
        return NO;
    }else{
        return YES;
    }
}
//- (void) showAlert
//{
//    //显示提示框
//    //过时
//    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"message" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
//    //    [alert show];
//    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"
//                                                                   message:@"您还没有登录,是否登录..."
//                                                            preferredStyle:UIAlertControllerStyleAlert];
//
//    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault
//                                                          handler:^(UIAlertAction * action) {
//                                                              //响应事件
//                                                              NSLog(@"action = %@", action);
//
//                                                          }];
//    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault
//                                                         handler:^(UIAlertAction * action) {
//                                                             //响应事件
//                                                             NSLog(@"action = %@", action);
//                                                         }];
//
//    [alert addAction:defaultAction];
//    [alert addAction:cancelAction];
//    [self presentViewController:alert animated:YES completion:nil];
//}
- (NSString *)md5:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    
    return result;
}

- (void)pushWithAnimationType:(NSString *)typeStr
{
    __weak typeof (self) weakself = self;
    [weakself.navigationController.view.layer addAnimation:[self createTransitionAnimation:typeStr] forKey:nil];
}
#pragma CATransition动画实现
/**
 动画类型
 fade 淡出效果
 moveIn 新视图移动到旧视图
 push 新视图推出旧视图
 reveal 移开旧视图
 cube 立方体翻转效果
 oglFlip 翻转效果
 suckEffect 收缩效果
 rippleEffect 水滴波纹效果
 pageCurl 向下翻页
 pageUnCurl 向上翻页
 CameraIrisHollowOpen, 开镜头
 CameraIrisHollowClose, 关镜头
 CurlDown,              下翻页
 CurlUp,                 上翻页
 FlipFromLeft,           左翻转
 FlipFromRight,          右翻转
 */
-(CATransition *)createTransitionAnimation:(NSString*)typeStr
{
    //切换之前添加动画效果
    //后面知识: Core Animation 核心动画
    //不要写成: CATransaction
    //创建CATransition动画对象
    CATransition *animation = [CATransition animation];
    //设置动画的类型:
    animation.type = typeStr;
    //设置动画的方向
    animation.subtype = kCATransitionFromBottom;
    //设置动画的持续时间
    animation.duration = 0.1;
    //设置动画速率(可变的)
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    //动画添加到切换的过程中
    return animation;
}
@end
